package com.share.ai.alibaba.dashscope.config;

import com.share.ai.alibaba.dashscope.tools.WeatherTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Scanner;

/**
 * CommandLineRunner 是启动时的命令行,执行完毕时会自动完毕
 * <p>
 * 不能过早的 停止客户端应用,否则演示失败
 */
@Slf4j
@ConditionalOnProperty(name = "mcpStartTest", havingValue = "true")
@Configuration
public class TestMcpByCommandLineV2 {

    @Bean
    public CommandLineRunner commandLineRunner(ChatClient.Builder builder, WeatherTool tool, ToolCallbackProvider mcpTools, ConfigurableApplicationContext context) {
        return args -> {
            Scanner scanner = new Scanner(System.in);
            ChatClient chatClient = builder.defaultTools(tool).defaultToolCallbacks(mcpTools).build();
            log.info("启动时开始执行命令,请输入你的问题, eg: 获取深圳的天气信息");
            while (true) {
                try {
                    String question = scanner.nextLine();
                    if ("exit".equals(question)) {
                        log.info("正在关闭应用容器...");
                        context.close();
                        log.info("应用容器已关闭");
                        System.exit(0); // 确保进程退出
                    }

                    log.info("正在请求ai 协助回答你的问题....");
                    String content = chatClient.prompt().user(question).call().content();

                    log.info("你的问题：{}", question);
                    log.info("Ai的回答：{}", content);

                } catch (Exception e) {
                    log.error("执行异常", e);
                } finally {
                    scanner.close();
                }
            }
        };
    }
}